const fs = require("fs");
const { themeList, writeFile } = require("../tool/util");
const { zhCN, enUS } = require("./zhCN");

function readFileContent(src) {
    if (fs.existsSync(src)) {
        return JSON.parse(fs.readFileSync(src, "utf-8"));
    }
    return "";
}

function writeFileContent(src, data) {
    if (fs.existsSync(src)) {
        writeFile(src, JSON.stringify(data, "", "\t"));
    }
}

// 获取lib下的全局配置
function getLibGlobalConfigBody(file) {
    const libConfigSrc = `./src/theme/${file}/lib/config/global.json`;
    if (fs.existsSync(libConfigSrc)) {
        return JSON.parse(fs.readFileSync(libConfigSrc, "utf-8"));
    }
    return "";
}

function getLibPageConfigBody(file) {
    const libConfigSrc = `./src/theme/${file}/lib/config/page.json`;
    if (fs.existsSync(libConfigSrc)) {
        return JSON.parse(fs.readFileSync(libConfigSrc, "utf-8"));
    }
    return "";
}

function writeLibGlobalConfigBody(file, data) {
    const libConfigSrc = `./src/theme/${file}/lib/config/global.json`;
    if (fs.existsSync(libConfigSrc)) {
        writeFile(libConfigSrc, JSON.stringify(data, "", "\t"));
    }
}

// 获取全局配置
function getGlobalConfigBody(file) {
    const libConfigSrc = `./src/theme/${file}/config/settings_schema.json`;
    if (fs.existsSync(libConfigSrc)) {
        return JSON.parse(fs.readFileSync(libConfigSrc, "utf-8"));
    }
    return "";
}

function writeGlobalConfigBody(file, data) {
    const libConfigSrc = `./src/theme/${file}/config/settings_schema.json`;
    if (fs.existsSync(libConfigSrc)) {
        writeFile(libConfigSrc, JSON.stringify(data, "", "\t"));
    }
}

function getGlobalConfigDataBody(file) {
    const libConfigSrc = `./src/theme/${file}/config/settings_data.json`;
    if (fs.existsSync(libConfigSrc)) {
        return JSON.parse(fs.readFileSync(libConfigSrc, "utf-8"));
    }
    return "";
}

function writeGlobalConfigDataBody(file, data) {
    const libConfigSrc = `./src/theme/${file}/config/settings_data.json`;
    if (fs.existsSync(libConfigSrc)) {
        writeFile(libConfigSrc, JSON.stringify(data, "", "\t"));
    }
}

function setConfigValue(settings, id, key, value) {
    settings.forEach((element) => {
        for (let i = 0; i < element.settings.length; i++) {
            const setting = element.settings[i];
            if (setting.id && setting.id === id) {
                setting[key] = value;
                break;
            }
        }
    });
    return settings;
}

// 更新全局设置
function updateGlobalConfig(theme) {
    //读取文件、查找变量、修改变量
    const libGlobal = getLibGlobalConfigBody(theme);

    var option = [
        {
            label: {
                zh_CN: "展示评分星级",
                en_US: "Displaying review ratings"
            },
            value: 1
        },
        {
            label: {
                zh_CN: "展示评分数量",
                en_US: "Displaying the number of reviews"
            },
            value: 2
        },
        {
            label: {
                zh_CN: "展示评分星级（数量）",
                en_US: "Displaying the number of stars"
            },
            value: 3
        }
    ];

    const label = {
        zh_CN: "评分展示",
        en_US: "Rating display"
    };

    if (libGlobal) {
        writeLibGlobalConfigBody(theme, setConfigValue(libGlobal, "product_is_score_number", "default", 1));
        writeLibGlobalConfigBody(theme, setConfigValue(libGlobal, "product_is_score_number", "option", option));
        writeLibGlobalConfigBody(theme, setConfigValue(libGlobal, "product_is_score_number", "label", label));
        writeLibGlobalConfigBody(theme, setConfigValue(libGlobal, "product_is_score_number", "type", "card_select"));
    }

    const globalData = getGlobalConfigDataBody(theme);
    if (globalData) {
        globalData.global.product_is_score_number = 1;
        writeGlobalConfigDataBody(theme, globalData);
    }

    const global = getGlobalConfigBody(theme);
    if (global) {
        global.global_setting = setConfigValue(global.global_setting, "product_is_score_number", "default", 1);
        global.global_setting = setConfigValue(global.global_setting, "product_is_score_number", "option", option);
        global.global_setting = setConfigValue(global.global_setting, "product_is_score_number", "label", label);
        global.global_setting = setConfigValue(global.global_setting, "product_is_score_number", "type", "card_select");

        writeGlobalConfigBody(theme, global);
    }
}

// 更新页面设置
function updatePageConfig(theme) {
    const newPageConfig = [
        {
            name: {
                zh_CN: "优惠码列表页"
            },
            route: "coupon/list",
            max_block: 20,
            route_handle: "",
            sections: [
                {
                    type: "header",
                    fixed: "top",
                    name: {
                        zh_CN: "页头"
                    }
                },
                {
                    type: "coupons_list",
                    fixed: "require",
                    name: {
                        zh_CN: "优惠券列表"
                    }
                },
                {
                    type: "footer",
                    fixed: "bottom",
                    name: {
                        zh_CN: "页尾"
                    }
                }
            ]
        },
        {
            name: {
                zh_CN: "优惠码详情页"
            },
            route: "coupon/detail",
            max_block: 20,
            route_handle: "",
            sections: [
                {
                    type: "header",
                    fixed: "top",
                    name: {
                        zh_CN: "页头"
                    }
                },
                {
                    type: "coupons_detail",
                    fixed: "require",
                    name: {
                        zh_CN: "优惠券详情"
                    }
                },
                {
                    type: "footer",
                    fixed: "bottom",
                    name: {
                        zh_CN: "页尾"
                    }
                }
            ]
        },
        {
            name: {
                zh_CN: "满减活动列表页"
            },
            route: "promotion/list",
            max_block: 20,
            route_handle: "",
            sections: [
                {
                    type: "header",
                    fixed: "top",
                    name: {
                        zh_CN: "页头"
                    }
                },
                {
                    type: "promotion_list",
                    fixed: "require",
                    name: {
                        zh_CN: "活动列表"
                    }
                },
                {
                    type: "footer",
                    fixed: "bottom",
                    name: {
                        zh_CN: "页尾"
                    }
                }
            ]
        },
        {
            name: {
                zh_CN: "满减活动详情页"
            },
            route: "promotion/detail",
            max_block: 20,
            route_handle: "",
            sections: [
                {
                    type: "header",
                    fixed: "top",
                    name: {
                        zh_CN: "页头"
                    }
                },
                {
                    type: "promotion_detail",
                    fixed: "require",
                    name: {
                        zh_CN: "活动详情"
                    }
                },
                {
                    type: "footer",
                    fixed: "bottom",
                    name: {
                        zh_CN: "页尾"
                    }
                }
            ]
        }
    ];
    const newLibPageConfig = [
        {
            name: {
                zh_CN: "优惠码列表页"
            },
            route: "coupon/list",
            max_block: 20,
            route_handle: "",
            layout: true,
            sections: [
                {
                    type: "coupons_list",
                    fixed: "require"
                }
            ]
        },
        {
            name: {
                zh_CN: "优惠码详情页"
            },
            route: "coupon/detail",
            max_block: 20,
            route_handle: "",
            layout: true,
            sections: [
                {
                    type: "coupons_detail",
                    fixed: "require"
                }
            ]
        },
        {
            name: {
                zh_CN: "满减活动列表页"
            },
            route: "promotion/list",
            max_block: 20,
            route_handle: "",
            layout: true,
            sections: [
                {
                    type: "promotion_list",
                    fixed: "require"
                }
            ]
        },
        {
            name: {
                zh_CN: "满减活动详情页"
            },
            route: "promotion/detail",
            max_block: 20,
            route_handle: "",
            layout: true,
            sections: [
                {
                    type: "promotion_detail",
                    fixed: "require"
                }
            ]
        }
    ];
    const libPageSrc = `./src/theme/${theme}/lib/config/page.json`;
    const libPage = readFileContent(libPageSrc);
    if (libPage) {
        const poorConfig = newLibPageConfig.filter((item) => {
            return libPage.find((page) => page.route === item.route) ? false : true;
        });
        poorConfig.forEach((page) => libPage.push(page));
        writeFileContent(libPageSrc, libPage);
    }

    // const globalSrc = `./src/theme/${theme}/config/settings_schema.json`;
    // const global = readFileContent(globalSrc);
    // if(global){
    //     const poorConfig = newPageConfig.filter((item)=>{
    //         return global.pages_setting.find(page=>page.route === item.route)?false:true
    //     })
    //     poorConfig.forEach(page=>global.pages_setting.push(page))
    //     writeFileContent(globalSrc,global)
    // }
}

// 更新配置信息
function upDatePageItemConfig(theme) {
    const globalSrc = `./src/theme/${theme}/config/settings_schema.json`;
    const global = readFileContent(globalSrc);
    if (global) {
        global.pages_setting.forEach((page) => {
            if (["product/detail", "collection/detail", "blog/list", "search/detail"].includes(page.route)) {
                page.sections.forEach(function (section) {
                    if (["product_detail", "collection_detail", "blog_list", "search_detail"].includes(section.type)) {
                        section.fixed = "require";
                    }
                });
            }
        });
        writeFileContent(globalSrc, global);
    }

    const settingsDataSrc = `./src/theme/${theme}/config/settings_data.json`;
    const settingsDataBody = readFileContent(settingsDataSrc);
    if (settingsDataBody) {
        settingsDataBody.pages_settings.forEach((page) => {
            if (["product/detail", "collection/detail", "blog/list", "search/detail"].includes(page.route)) {
                page.sections.forEach(function (section) {
                    if (["product_detail", "collection_detail", "blog_list", "search_detail"].includes(section.type)) {
                        section.fixed = 4;
                    }
                });
            }
        });
        writeFileContent(settingsDataSrc, settingsDataBody);
    }

    const pageSrc = `./src/theme/${theme}/lib/config/page.json`;
    const pageBody = readFileContent(pageSrc);
    if (pageBody) {
        pageBody.forEach((page) => {
            if (["product/detail", "collection/detail", "blog/list", "search/detail"].includes(page.route)) {
                page.sections.forEach(function (section) {
                    if (["product_detail", "collection_detail", "blog_list", "search_detail"].includes(section.type)) {
                        section.fixed = "require";
                    }
                });
            }
        });
        writeFileContent(pageSrc, pageBody);
    }
}

// 全局配置差异
function globalDifferences() {
    const defaultGlobal = readFileContent(`./src/theme/default/lib/config/global.json`);

    let defaultGlobalIDKey = [];
    defaultGlobal.forEach((item) => {
        item.settings.forEach((setting) => {
            setting.id && defaultGlobalIDKey.push(setting.id);
        });
    });

    const themes = themeList();
    themes.forEach((theme) => {
        const themeData = readFileContent(`./src/theme/${theme}/lib/config/global.json`);
        if (themeData) {
            themeData.forEach((item) => {
                item.settings.forEach((setting) => {
                    if (setting.id && !defaultGlobalIDKey.includes(setting.id)) {
                        console.log("差距模版:", theme, setting.id);
                    }
                });
            });
        }
    });
}

function main() {
    //globalDifferences();
    // updateGlobalConfig("default")
    const themes = themeList();
    themes.forEach((theme) => {
        updateGlobalConfig(theme);
    });
}

main();
